﻿using Grow.Module.Service;

namespace Grow.Domain.Repository.EntityFrameworkCore
{
    public abstract class UnitOfWorkManagerBase : IUnitOfWorkManager
    {
        private bool disposedValue;
        public IUnitOfWork? CurrUnitOfWork { get; set; }

        protected readonly IServiceContext _serviceContext;
        public UnitOfWorkManagerBase(IServiceContext serviceContext)
        {
            _serviceContext = serviceContext;
        }

        public IUnitOfWork GetUnitOfWork()
        {
            if (CurrUnitOfWork is null)
            {
                UnitOfWorkOptions dbOptions = _serviceContext.GetOptions<UnitOfWorkOptions>();

                CurrUnitOfWork = new UnitOfWork(GetDefaultDbContext(dbOptions));
            }

            return CurrUnitOfWork;
        }
        public abstract IDbContext GetDefaultDbContext(UnitOfWorkOptions dbOptions);
        #region Dispose
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    CurrUnitOfWork?.Dispose();
                }

                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~UnitOfWorkManagerBase()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        void IDisposable.Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
        #endregion


    }
}